import { IRouteItem } from '@/routers/routerConfig';
import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Layout, Menu } from 'antd';
import { cloneDeep, isEmpty } from 'lodash-es';
import { useEffect, useMemo, useState } from 'react';
import { useLocation, useMatch, useNavigate } from 'react-router-dom';

type MenuItem = Required<MenuProps>['items'];

const { Sider } = Layout;

function MenuContent(props: { collapsed: boolean; routes: IRouteItem[] }) {
  const location = useLocation();
  const navigator = useNavigate();
  const { collapsed, routes } = props;
  const [selectedKeys, setSelectedKeys] = useState<string[]>();
  const [openKeys, setOpenKeys] = useState<string[]>();

  // 过滤掉hidden:true的routeItem
  function filtrateHideRoute(routesParams: IRouteItem[]): IRouteItem[] {
    const newRoutes = routesParams.filter((routeItem: IRouteItem) => !routeItem.hidden);
    for (let i = 0; i < newRoutes.length; i++) {
      if (newRoutes[i].children && newRoutes[i].children!.length > 0) {
        newRoutes[i].children = filtrateHideRoute(newRoutes[i].children!);
      }
    }

    return newRoutes;
  }

  //查找当前routeItem
  function getCurrMenuItem(menuKey: string, routes: IRouteItem[]): IRouteItem | undefined {
    for (let i = 0; i < routes.length; i++) {
      if (routes[i].key === menuKey) {
        return routes[i];
      } else if (!isEmpty(routes[i].children)) {
        const tempItem = getCurrMenuItem(menuKey, routes[i].children!);
        if (tempItem) return tempItem;
      }
    }
  }

  const menuItems: MenuItem = useMemo(() => {
    const newFilterRoutes = filtrateHideRoute(cloneDeep(routes));
    return newFilterRoutes.map((item: IRouteItem) => {
      const { key, label, icon, children } = item;
      return {
        key,
        label,
        icon,
        children,
      };
    });
  }, []);
  // console.log('--menuItems--:', menuItems);

  useEffect(() => {
    // console.log('--LeftMenu--location.pathname--:', location.pathname);
    if (location.pathname && location.pathname !== '/') {
      const pathnames = location.pathname.split('/').filter((name: string) => name);
      // console.log('--leftMenu--pathnames--:', pathnames);
      let sKey = pathnames[pathnames.length - 1];
      // const currRouteItem = getCurrMenuItem(sKey, routes);
      // console.log('--sKey--currRouteItem--:', sKey, currRouteItem);
      setSelectedKeys([sKey]);
      setOpenKeys(pathnames);
    }
    // console.log('--LeftMenu--match---:', match);
  }, [location.pathname]);

  // ----- menu 事件 1,2 会同时触发
  // 1.菜单选中
  const onMenuSelect: MenuProps['onSelect'] = ({ key, keyPath, selectedKeys, domEvent }) => {
    console.log('--onSelect--key--keyPath--selectedKeys--:', key, keyPath, selectedKeys);
    const path: string = keyPath.reverse().join('/');
    navigator(path);
  };

  //2.点击
  const onMenuItemClick: MenuProps['onClick'] = ({ key, keyPath, domEvent }) => {
    // console.log('--onMenuItemClick--key--keyPath--:', key, keyPath);
  };

  //3. 打开关闭
  const onMenuOpenChange: MenuProps['onOpenChange'] = (openKeys: string[]) => {
    console.log('--onMenuOpenChange--openKeys--:', openKeys);
    setOpenKeys(openKeys);
  };
  return (
    <div className="safe-edu-menu_content">
      <Menu
        mode="inline"
        theme="light"
        // inlineCollapsed={collapsed}
        items={menuItems}
        selectedKeys={selectedKeys}
        openKeys={openKeys}
        onSelect={onMenuSelect}
        onClick={onMenuItemClick}
        onOpenChange={onMenuOpenChange}
      />
    </div>
  );
}

function LeftMenu(props: { routes: IRouteItem[] }) {
  // 折叠情况
  const [collapsed, setCollapsed] = useState(false);
  return (
    <Sider
      theme="light"
      collapsedWidth={64}
      collapsible
      collapsed={collapsed}
      trigger={null}
      onCollapse={(value) => setCollapsed(value)}
    >
      <MenuContent collapsed={collapsed} routes={props.routes} />
      <div className="collapse-trigger-container">
        <div
          className="collapse-trigger"
          onClick={() => {
            setCollapsed(!collapsed);
          }}
        >
          {collapsed ? (
            <CaretRightOutlined style={{ color: '#7B8086' }} />
          ) : (
            <CaretLeftOutlined style={{ color: '#7B8086' }} />
          )}
        </div>
      </div>
    </Sider>
  );
}

export default LeftMenu;
